<template>
    <div class="browser-page" ><!--:class="{hidden:!isActive}"-->
        <webview ref="webview" :class="{'full-screen':isFullScreen}" :preload="preload" @contextmenu="this.$parent.onContextMenu" partition="persist:github" webpreferences="defaultFontFamily.standard='Microsoft Yahei'"/>
        <chrome-frame-status :status="status"/>
    </div>
</template>
<script>
    import process from 'process'
    import ChromeFrameStatus from './ChromeFrameStatus'
    import { remote } from 'electron';

    export default {
        props: ['bPage','tabbar','index'],
        data(){
            return {
                lastTargetURL: '',
                isFullScreen: false
            }
        },
        computed: {
            page: function () {
                return this.$parent.pages[this.$parent.currentPageIndex];
            },
            searchInput: function () {
                return {
                    isActive: this.page.isSearching,
                    onPageSearch: this.onPageSearch
                }
            },
            status: function () {
                return {
                    page: this.page
                }
            },
            // isActive: function () {
            //     return this.index == this.$parent.currentPageIndex;
            // },
            preload: function () {
                return "file:///" + process.cwd() + "/app/dist/electron/preload/main.js";
            }
        },
        beforeDestroy: function () {
            window.removeEventListener('resize', resize);
        },
        mounted() {

            const webview = this.$refs['webview']

            this.webview = webview
            this.win = remote.getCurrentWindow()

            webview.addEventListener('new-window', this.newWindow)
            webview.addEventListener('update-target-url', (e) => this.lastTargetURL = e.url)

            webview.addEventListener('enter-html-full-screen', () => {
                this.win.setAlwaysOnTop(true)
                this.isFullScreen = true
            })

            webview.addEventListener('leave-html-full-screen', () => {
                this.win.setAlwaysOnTop(false)
                this.isFullScreen = false
            })

            // setup resize events
            // window.addEventListener('resize', resize)
            // resize()

            // attach webview events
            for (var k in webviewEvents)
                webview.addEventListener(k, webviewHandler(this, webviewEvents[k]))

            // set location, if given
            if (this.page.location)
                this.navigateTo(this.page.location);


        },
        methods: {
            newWindow(e){
                const protocol = require('url').parse(e.url).protocol
                let url = 'about:blank'
                if (protocol === 'http:' || protocol === 'https:') {
                    url = e.url
                } else if(e.disposition === 'new-window' && e.url === "about:blank" && this.lastTargetURL !== ''){
                    url = this.lastTargetURL
                }
                this.tabbar.onNewWindow(url)
            },
            navigateTo: function (l) {
                this.$refs.webview.setAttribute('src', l)
            },

            onPageSearch: function (query) {
                this.$refs.webview.executeJavaScript('window.find("' + query + '", 0, 0, 1)')
            }
        },
        components: {
            ChromeFrameStatus
        }
    }

    function webviewHandler(self, fnName) {
        return function (e) {
            if (self.$parent[fnName])
                self.$parent[fnName](e, self.page, self.index)
        }
    }

    var webviewEvents = {
        'load-commit': 'onLoadCommit',
        'did-start-loading': 'onDidStartLoading',
        'did-stop-loading': 'onDidStopLoading',
        'did-finish-load': 'onDidFinishLoading',
        'did-fail-load': 'onDidFailLoad',
        'did-get-response-details': 'onDidGetResponseDetails',
        'did-get-redirect-request': 'onDidGetRedirectRequest',
        'dom-ready': 'onDomReady',
        'page-title-set': 'onPageTitleSet',
        'close': 'onClose',
        'destroyed': 'onDestroyed',
        'ipc-message': 'onIpcMessage',
        'console-message': 'onConsoleMessage'
    }

    function resize() {
        // console.log("resize fired.")
        Array.prototype.forEach.call(document.querySelectorAll('webview'), function (webview) {
            var obj = webview && webview.querySelector('::shadow object')
            if (obj)
                obj.style.height = (window.innerHeight - 59) + 'px' // -61 to adjust for the tabs and navbar regions
        })
    }
</script>
<style lang="css">
    /*#browser-page {
        position: relative;
          width: 100%;
            min-height: 100%;
    }*/
    .browser-page {
        /*position: absolute;*/
        /*top: 0;*/
        /*left: 0;*/
        width: 100%;
        height: 100%;
        /*z-index: 1;*/
        /*background-color: #fff;*/
    }

    /*.browser-page:not(.hidden){*/
    /*    z-index: 100;*/
    /*}*/

    webview {
        border: 0;
        width: 100%;
        min-height: 100%;
        /* This fix Edge */
    }

    webview.full-screen{
         position: fixed;
         top: 0;
         left: 0;
         z-index: 100;
     }

    .hidden {
        /*display: none;*/
    }


</style>
